package com.gipson.amc.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsbj.common.msg.DataPageMessage;
import com.dsbj.common.msg.ResponseMessage;
import com.gipson.amc.entity.*;
import com.gipson.amc.model.TreeNode;
import com.gipson.amc.service.basicdata.ApplicationService;
import com.gipson.amc.service.basicdata.PostGroupService;
import com.gipson.amc.service.basicdata.RoleService;
import com.gipson.amc.service.basicdata.UserService;
import com.gipson.amc.utils.PasswordHelper;
import com.gipson.amc.utils.security.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户管理 前端控制器
 * </p>
 *
 * @author xsyuan
 * @since 2020-03-27
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;
    
    @Resource
    private ApplicationService applicationService;
    
    @Resource
    private PostGroupService postGroupService;

    @RequestMapping("/list")
    @RequiresPermissions("user.list")
    public String list(){
        return "basicdata/user/list";
    }
    
    /**
     * @description 详情页面
     * @param
     * @author: xsyuan 2020/6/8 14:26
     * @return
     */
    @RequestMapping("/detail")
    @RequiresPermissions("user.list")
    public String detail(Model model ,String id){
        User user= userService.getById(id==null?"":id);
        model.addAttribute("user",user);
        return "basicdata/user/detail";
    }

    @RequestMapping("/ajaxPageInfo")
    @RequiresPermissions("user.list")
    @ResponseBody
    public DataPageMessage hazardPageInfo(User user, PageByDataTable pageByDataTable){
        Page<User> userPage =userService.selectPageForUser(user,pageByDataTable);
        return DataPageMessage.ok(userPage.getRecords(),(int)userPage.getTotal(),(int)userPage.getTotal(),pageByDataTable.getSEcho(),"");
    }
    
    /**
     * @description  编辑用户
     * @param
     * @author: xsyuan 2020/5/21 15:54
     * @return
     */
    @RequestMapping("/edit")
    @RequiresPermissions(value = {"user.add","user.edit"},logical = Logical.OR)
    public String edit (Model model, String id){
        User user= userService.getById(id==null?"":id);
        model.addAttribute("user",user);
        return "basicdata/user/edit";
    }
    
 /**
   * @description 通过用户ID查询所拥有的的【岗位】
   * @param
   * @author: xsyuan 2020/5/21 15:54
   * @return
   */
    @RequestMapping("/getPostGroupByUserId")
    @RequiresPermissions(value = {"user.add","user.edit"},logical = Logical.OR)
    @ResponseBody
    public ResponseMessage getPostGroupByUserId(String userId){
        User user= userService.getById(userId==null?"":userId);
        List<PostGroup> postGroupList = new  ArrayList();
        if(user==null){
            user = new User();
        }else{
            //查询用户岗位
            postGroupList = postGroupService.getPostGroupsByUserId(user.getId()==null?"":user.getId());
        }
        return ResponseMessage.ok(postGroupList);
    }
/********************************** 分配岗位 方式一 (平铺式分页) START *************************************************************************/
    /**
     * @description  分配用户岗位
     * @param
     * @author: xsyuan 2020/5/12 15:28
     * @return
     */
    @RequestMapping("selectUserPostGroup")
    @RequiresPermissions(value = {"user.add","user.edit"},logical = Logical.OR)
    public String selectUserPostGroup(Model model,String postGroupIdNotIn,String companyCode) {
        model.addAttribute("postGroupIdNotIn",postGroupIdNotIn);
        model.addAttribute("companyCode",companyCode);
        return "basicdata/user/selectUserPostGroup";
    }
 /**
   * @description  岗位分页数据
   * @param
   * @author: xsyuan 2020/5/22 13:01
   * @return
   */
    @RequestMapping("/ajaxPostGroupPageInfo")
    @ResponseBody
    public DataPageMessage ajaxPostGroupPageInfo(PostGroup postGroup,PageByDataTable pageByDataTable){
        Page<PostGroup> postGroupPage =postGroupService.getPostGroupPage(postGroup,pageByDataTable);
        if(postGroupPage==null||postGroupPage.getRecords()==null){
            return DataPageMessage.ok(null,(int)postGroupPage.getCurrent(),(int)postGroupPage.getCurrent(),pageByDataTable.getSEcho(),"");
        }
        return DataPageMessage.ok(postGroupPage.getRecords(),(int)postGroupPage.getTotal(),(int)postGroupPage.getTotal(),pageByDataTable.getSEcho(),"");
    }
    
    /**
     * @description 通过用户ID查询所拥有的的【角色】
     * @param
     * @author: xsyuan 2020/5/21 15:54
     * @return
     */
    @RequestMapping("/getRoleByUserId")
    @RequiresPermissions(value = {"user.add","user.edit"},logical = Logical.OR)
    @ResponseBody
    public ResponseMessage getRoleByUserId(String userId){
        User user= userService.getById(userId==null?"":userId);
        List<Role> roleList = new  ArrayList();
        if(user==null){
            user = new User();
        }else{
            //查询用户角色
            roleList = roleService.getRolesByUsername(user.getUsername()==null?"":user.getUsername());
        }
        return ResponseMessage.ok(roleList);
    }
/********************************** 分配岗位 方式一 (平铺式分页) END *************************************************************************/

/********************************** 分配岗位 方式二 (树形结构) START *************************************************************************/
    
    @RequestMapping("selectUserPostGroupByTree")
    @RequiresPermissions(value = {"user.add","user.edit"},logical = Logical.OR)
    public String selectUserPostGroupByTree(Model model,String postGroupIdNotIn,String companyCode) {
        List<TreeNode> treeList = postGroupService.getTreeData(companyCode,postGroupIdNotIn);
        String json = JSONArray.toJSONString(treeList);
        model.addAttribute("trees",json);
        return "basicdata/user/selectUserPostGroupByTree";
    }


/********************************** 分配岗位 方式二 (树形结构) END *************************************************************************/
    
    /**
     * @description  分配用户角色
     * @param
     * @author: xsyuan 2020/5/12 15:28
     * @return
     */
    @RequestMapping("selectUserRole")
    @RequiresPermissions(value = {"user.add","user.edit"},logical = Logical.OR)
    public String selectUserRole(Model model,String roleIdNotIn,String userId) {
        List<Application> applicationList = applicationService.list(Wrappers.<Application>lambdaQuery()
                .eq(Application::getDelFlag,0)
                .orderByAsc(Application::getSort)
        );
        model.addAttribute("applicationList",applicationList);
        model.addAttribute("roleIdNotIn",roleIdNotIn);
        model.addAttribute("userId",userId);
        return "basicdata/user/selectUserRole";
    }
    
    
 /**
   * @description 删除用户
   * @param
   * @author: xsyuan 2020/5/21 15:48
   * @return
   */
    @RequestMapping("/del")
    @RequiresPermissions("user.delete")
    @ResponseBody
    public ResponseMessage del (String ids){
        return userService.delBatch(ids);
    }

 /**
   * @description 保存用户数据
   * @param
   * @author: xsyuan 2020/5/21 15:49
   * @return
   */
    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"user.add","user.edit"},logical = Logical.OR)
    @ResponseBody
    public ResponseMessage saveOrUpdate( User user,String roleIds,String postGroupIds){
        return  userService.saveOrUpdateByUser(user,roleIds,postGroupIds);
    }
    /**
     * @description 修改密码
     * @param
     * @author: xsyuan 2020/5/21 15:48
     * @return
     */
    @RequestMapping("/passwordedit")
    @RequiresPermissions("user.password.edit")
    public String passwordedit (){
        return "basicdata/user/passwordedit";
    }
    
 /**
   * @description 修改保存密码
   * @param
   * @author: xsyuan 2020/5/21 15:56
   * @return
   */
    @RequestMapping("/saveByPassword")
    @RequiresPermissions("user.password.edit")
    @ResponseBody
    public ResponseMessage saveByPassword(String amcOldPassword,String amcNewPassword){
       return userService.saveByPassword(amcOldPassword,amcNewPassword);
    }
}
